﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CPPEI.ETL.Domain.Entities;
using CPPEI.ETL.Domain.Services;
using CPPEI.ETL.Infrastructure.Excel;
using CPPEI.ETL.Infrastructure.OpenXml;
using CPPEI.ETL.Infrastructure.SMS;

namespace CPPEI.ETL.Domain.MessageAlert
{
    public class SMSAlert
    {

        XmlHelper _xmlhelper = new XmlHelper(System.Configuration.ConfigurationManager.AppSettings["SendSMSConfig"]);

        public bool SendSMS(EtlDbContext dbContext, string taskName, DateTime errorDate, string runMode)
        {
            try
            {
                var content =
                    _xmlhelper.GetValue("Content")
                        .Replace("{{TaskName}}", taskName)
                        .Replace("{{ErrorTime}}", errorDate.ToString("yyyyMMdd HH:mm:ss"))
                        .Replace("{{RunModel}}", runMode);
                //发送邮件通知
                var _hlper = new SMSHelper();
                List<string> mobileList = new List<string>();
                List<string> noSendmobileList = new List<string>();
                var list = dbContext.Set<Entities.Maintainer>().Where(p => p.Mobile != "");
                DateTime now = DateTime.Now;
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        var stime = item.StartTime.Split(':');
                        var etime = item.EndTime.Split(':');
                        DateTime startTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(stime[0]),
                            Convert.ToInt32(stime[1]), Convert.ToInt32(stime[2]));
                        DateTime endTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(etime[0]),
                            Convert.ToInt32(etime[1]), Convert.ToInt32(etime[2]));
                        if (startTime <= now && endTime >= now)
                            mobileList.Add(item.Mobile);
                        else
                            noSendmobileList.Add(item.Mobile);
                    }
                }

                #region 发送信息并插入记录

                if (mobileList.Any())
                {
                    foreach (var item in mobileList.Distinct())
                    {
                        var result = _hlper.SendOnce("", content, item);
                        if (result.IsSuccess)
                        {
                            dbContext.Set<EMessageAlertRecord>().Add(new EMessageAlertRecord()
                            {
                                Id = Guid.NewGuid(),
                                AlertType = (int) MessageAlertRecordAlertType.SMS,
                                Address = item,
                                Content = content,
                                Title = "",
                                CreatedTime = DateTime.Now,
                                Description = result.Data.BatchId.ToString(),
                                IsSuccess = (int) MessageAlertRecordIsSuccess.Success
                            });
                        }
                        else
                        {
                            dbContext.Set<EMessageAlertRecord>().Add(new EMessageAlertRecord()
                            {
                                Id = Guid.NewGuid(),
                                AlertType = (int) MessageAlertRecordAlertType.SMS,
                                Address = item,
                                Content = content,
                                Title = "",
                                CreatedTime = DateTime.Now,
                                Description = result.Message,
                                IsSuccess = (int) MessageAlertRecordIsSuccess.Fail
                            });
                        }
                    }
                }

                #endregion

                #region 插入等待发送的信息

                if (noSendmobileList.Any())
                {
                    foreach (var item in noSendmobileList.Distinct())
                    {
                        dbContext.Set<EMessageAlertRecord>().Add(new EMessageAlertRecord()
                        {
                            Id = Guid.NewGuid(),
                            AlertType = (int) MessageAlertRecordAlertType.SMS,
                            Address = item,
                            Content = content,
                            Title = "",
                            CreatedTime = DateTime.Now,
                            Description = "",
                            IsSuccess = (int) MessageAlertRecordIsSuccess.WaitSend
                        });
                    }

                }

                #endregion

                return dbContext.SaveChanges() >= 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void TestSms()
        {
            using (EtlDbContext dbContext = new EtlDbContext())
            {
                //发送邮件通知
                var _hlper = new SMSHelper();
                List<Maintainer> mobileList = new List<Maintainer>();
                DateTime now = DateTime.Now;
                var list = dbContext.Set<Entities.Maintainer>().Where(p => p.Mobile != "");
                if (list.Any())
                {
                    foreach (var item in list)
                    {
                        var stime = item.StartTime.Split(':');
                        var etime = item.EndTime.Split(':');
                        DateTime startTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(stime[0]),
                            Convert.ToInt32(stime[1]), Convert.ToInt32(stime[2]));
                        DateTime endTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(etime[0]),
                            Convert.ToInt32(etime[1]), Convert.ToInt32(etime[2]));
                        if (startTime <= now && endTime >= now)
                            mobileList.Add(item);
                    }
                }
                if (mobileList.Any())
                {
                    var lastdate = new DateTime(now.Year, now.Month, now.Day).AddDays(-1);
                    var waitsendmsg = dbContext.Set<Entities.EMessageAlertRecord>().Where(p =>
                        p.CreatedTime >= lastdate
                        && p.IsSuccess == (int) MessageAlertRecordIsSuccess.WaitSend
                        && p.AlertType == (int) MessageAlertRecordAlertType.SMS).ToList();
                    IList<EMessageAlertRecord> tempmsg = null;
                    if (waitsendmsg.Any())
                    {
                        foreach (var item in mobileList)
                        {
                            var stime = item.StartTime.Split(':');
                            var etime = item.EndTime.Split(':');
                            DateTime startTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(stime[0]),
                                Convert.ToInt32(stime[1]), Convert.ToInt32(stime[2]));
                            DateTime endTime = new DateTime(now.Year, now.Month, now.Day, Convert.ToInt32(etime[0]),
                                Convert.ToInt32(etime[1]), Convert.ToInt32(etime[2]));
                            if (startTime > endTime)
                                throw new Exception("开始日期不能大于结束日期");
                            endTime = endTime.AddDays(-1); //获取前一天的结束日期
                            tempmsg =
                                waitsendmsg.Where(
                                    x =>
                                        x.Address == item.Mobile && startTime >= x.CreatedTime &&
                                        endTime <= x.CreatedTime).ToList();
                            foreach (var msg in tempmsg)
                            {
                                try
                                {
                                    var result = _hlper.SendOnce("", msg.Content, item.Mobile);
                                    msg.IsSuccess = result.IsSuccess
                                        ? (int) MessageAlertRecordIsSuccess.Success
                                        : (int) MessageAlertRecordIsSuccess.Fail;
                                    msg.Description = result.IsSuccess ? result.Data.BatchId.ToString() : "";
                                }
                                catch (Exception ex)
                                {
                                    msg.IsSuccess = -1;
                                    msg.Description = "";
                                }
                                finally
                                {
                                    dbContext.Set<EMessageAlertRecord>().Attach(msg);
                                    dbContext.Entry(msg).State = EntityState.Modified;
                                }
                            }
                        }
                        dbContext.SaveChanges();
                    }
                }
            }
        }


    }
}
